package com.hitcoder.common

import android.text.TextUtils
import android.util.Log
import com.google.gson.Gson
import com.hitcoder.network.NetWorkApi
import com.hitcoder.network.exceptions.ServerException
import com.hitcoder.network.utils.enqueueEx
import com.hitcoder.network.utils.executeEx
import com.hitcoder.network.utils.toJsonRequestBody
import okhttp3.RequestBody
import retrofit2.Call

val net = NetWorkApi.Builder
    .setBaseUrl("http://localhost:8118/")
    .setErrorHandler {
        when (it) {
            is NetResponse<*> -> {
                Log.e("TAG", "类型匹配成功")
                if (!TextUtils.equals(it.status.code, "1")) {
                    throw ServerException(-1, "网络接口调用失败")
                }
            }
        }
    }
    .setDebug(true)
    .setTimeout(30)
    .build()


fun <T> Call<T>.exe() = executeEx(net.appErrorHandler)

fun <T> Call<T>.enQ(callback: (code: Int, message: String, data: T?) -> Unit) =
    enqueueEx(callback, net.appErrorHandler)


/**
 * 封装请求参数
 */
fun <T> requestBody(params: T): RequestBody {
    val netRequest = NetRequest("03815d7a-ee06-48de-8893-c6c4aa0cc835", "", "", "", params)
    val jsonString = Gson().toJson(netRequest)
    return jsonString.toJsonRequestBody()
}